package Servlet;
/**
 * 项目名称：demoServlet.java
 * 文件名称：demoServlet.java
 * 类的描述：无
 * 创建时间：2025-07-17 15:26:43
 * 创建人：大帅比
 * <p>
 * 版权声明：本文件归 大帅比 所有，未经授权不得进行商业使用。
 */

import java.io.*;
import java.util.concurrent.ConcurrentHashMap;

import Entity.stu;
import Util.GokJDBCUtil2;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

@WebServlet("/login")
public class loginServlet extends HttpServlet {
    private static final ConcurrentHashMap<Integer, HttpSession> activeSessions = new ConcurrentHashMap<>();
    private static int count = 0;

    public void init() {
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        String name = req.getParameter("name");
        String pass = req.getParameter("pass");
        res.setCharacterEncoding("utf-8");
        res.setContentType("text/html;charset=UTF-8");
//        res.setContentType("application/json");
        stu p = GokJDBCUtil2.queryForObject("select id,name,age,sex from user where name=? and pass=?", stu.class, name, pass);
        if (p != null) {
            HttpSession session = req.getSession();
            session.setAttribute("user", p.getName());
            session.setAttribute("id", p.getId());
            session.setMaxInactiveInterval(60 * 60);
            PrintWriter writer = res.getWriter();
            writer.println("{\"code\":200,\"msg\":\"登录成功\"}");
            writer.close();
            count++;
            ServletContext context = req.getServletContext();
            context.setAttribute("count", count);
            // 2. 移除旧会话
            HttpSession existingSessionId = activeSessions.get(session.getAttribute("id"));
            if (existingSessionId != null) {
                // 3. 使旧会话失效
                activeSessions.remove(existingSessionId.getAttribute("id"));
                try {
                    existingSessionId.invalidate();
                } catch (Exception e) {
                }
                count--;
                context.setAttribute("count", count);
            }
            activeSessions.put((Integer) session.getAttribute("id"), session);
        } else {
            PrintWriter writer = res.getWriter();
            writer.println("{\"code\":400,\"msg\":\"用户名或者密码错误\"}");
            writer.close();
        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String method = req.getMethod();
        if (method.equals("GET")) {
            this.doGet(req, res);
        } else {
            PrintWriter writer = res.getWriter();
            res.setCharacterEncoding("utf-8");
            res.setContentType("application/json");
            writer.println("{\"code\":\"400\",\"msg\":\"此方法不允许\"}");
            writer.close();
        }
    }

    public void destroy() {
    }
}